﻿using System;
using JetBrains.Annotations;
using JetBrains.Application.Progress;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Intentions.Extensibility;
using JetBrains.TextControl;
using JetBrains.UI.BulbMenu;
using JetBrains.UI.RichText;

namespace MugenMvvmToolkit.ReSharper.Infrastructure
{
    public class DelegateBulbAction : BulbActionBase, IBulbItemRichText
    {
        #region Fields

        private readonly Func<ISolution, IProgressIndicator, Action<ITextControl>> _execute;

        #endregion

        #region Constructors

        /// <summary>
        ///     Initializes a new instance of the <see cref="DelegateBulbAction" /> class.
        /// </summary>
        public DelegateBulbAction([NotNull] Action<ISolution, IProgressIndicator> execute,
            [NotNull] RichText text)
            : this((solution, indicator) =>
            {
                execute(solution, indicator);
                return null;
            }, text)
        {
            if (execute == null) throw new ArgumentNullException("execute");
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="DelegateBulbAction" /> class.
        /// </summary>
        public DelegateBulbAction([NotNull] Func<ISolution, IProgressIndicator, Action<ITextControl>> func,
            [NotNull] RichText text)
        {
            if (func == null) throw new ArgumentNullException("func");
            if (text == null) throw new ArgumentNullException("text");
            _execute = func;
            RichText = text;
        }

        #endregion

        #region Implementation of IBulbAction

        /// <summary>
        ///     The text rendered directly on the bulb item.
        /// </summary>
        public override string Text
        {
            get { return RichText; }
        }

        /// <summary>
        ///     Executes QuickFix or ContextAction. Returns post-execute method.
        /// </summary>
        /// <returns>
        ///     Action to execute after document and PSI transaction finish. Use to open TextControls, navigate caret, etc.
        /// </returns>
        protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            return _execute(solution, progress);
        }

        #endregion

        #region Implementation of IBulbItemRichText

        /// <summary>
        ///     Text to be displayed on the bulb item.
        /// </summary>
        public RichText RichText { get; private set; }

        #endregion
    }
}